package com.ruoyi.common.baseImg;



import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;


public class Base64Utils {
    /**
     * base64字符串转换成图片
     * imgStr base64字符串
     * path 生成图片路径
     * photoName 图片名称
     */
    public static boolean GenerateImage(String imgStr, String path,String photoName) {
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            String baseValue = imgStr.replaceAll(" ", "+");
            byte[] b = decoder.decodeBuffer(baseValue.replace("data:image/jpeg;base64,", ""));
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            File targetFile = new File(path);
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            OutputStream out = new FileOutputStream(path+"/"+photoName);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    public static boolean GenerateImagePNG(String imgStr, String path,String photoName) {
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            String baseValue = imgStr.replaceAll(" ", "+");
            byte[] b = decoder.decodeBuffer(baseValue.replace("data:image/png;base64,", ""));
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            File targetFile = new File(path);
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            OutputStream out = new FileOutputStream(path+"/"+photoName);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    public static boolean GenerateImageJPG(String imgStr, String path,String photoName) {

        try {
            // 去掉base64前缀 data:image/jpeg;base64,
            imgStr = imgStr.substring(imgStr.indexOf(",", 1) + 1);
            // 解密，解密的结果是一个byte数组
            Base64.Decoder decoder = Base64.getDecoder();
            byte[] imgbytes = decoder.decode(imgStr);
            for (int i = 0; i < imgbytes.length; ++i) {
                if (imgbytes[i] < 0) {
                    imgbytes[i] += 256;
                }
            }

            // 保存图片
            OutputStream out = new FileOutputStream(path+"/"+photoName);
            out.write(imgbytes);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return true;
    }


}
